package com.xul.yygh.order.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.xul.yygh.order.service.OrderInfoService;
import com.xul.yygh.order.service.PaymentService;
import com.xul.yygh.order.service.RefundInfoService;
import com.xul.yygh.order.service.WeixinService;
import com.xul.yygh.order.utils.ConstantPropertiesUtils;
import com.xul.yygh.order.utils.HttpClient;
import model.com.xul.yygh.enums.PaymentTypeEnum;
import model.com.xul.yygh.enums.RefundStatusEnum;
import model.com.xul.yygh.model.order.OrderInfo;
import model.com.xul.yygh.model.order.PaymentInfo;
import model.com.xul.yygh.model.order.RefundInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author xul
 * @create 2021-07-20 19:18
 */
@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundInfoService refundInfoService;

    /**
     * 生成微信支付二维码
     *
     * @param orderId
     * @return
     */
    @Override
    public Map createNative(Long orderId) {

        try {
            // 从redis中获取数据
            Map payMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
            if (payMap != null) {
                return payMap;
            }

            // 1.根据orderId获取到订单的信息
            OrderInfo order = orderInfoService.getById(orderId);
            // 2.向支付纪录里面添加信息
            paymentService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus());
            // 3.设置参数 调用微信生成二维码的接口  把参数转换成为xml格式 使用商户key经行加密
            Map paramMap = new HashMap();
            // 商户id
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            // 商户号
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            // 微信工具类随机生成的字符串
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            // 主题的信息
            String body = order.getReserveDate() + "就诊" + order.getDepname();
            paramMap.put("body", body);
            // 订单的唯一编号
            paramMap.put("out_trade_no", order.getOutTradeNo());
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            // 订单的金额 此次测试写成0.01元
            paramMap.put("total_fee", "1");
            paramMap.put("spbill_create_ip", "127.0.0.1");
            // 回调地址 暂时没用到
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            // 类型的扫描支付
            paramMap.put("trade_type", "NATIVE");
            // 4.HTTPClient来根据URL访问第三方接口并且传递参数(调用微信生成二维码接口)
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            // client设置参数 ConstantPropertiesUtils.PARTNERKEY是商户的key 经行xml格式的加密
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            // 设置支持https请求
            client.setHttps(true);
            // 完成发送
            client.post();
            // 5.微信段会返回相关数据
            String xml = client.getContent();
            // 把xml转换成map集合
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("resultMap: " + resultMap);
            // 6.封装返回的数据集
            Map map = new HashMap<>();
            // 返回订单id
            map.put("orderId", orderId);
            // 返回订单金额
            map.put("totalFee", order.getAmount());
            // 返回状态码
            map.put("resultCode", resultMap.get("result_code"));
            // 返回二维码地址
            map.put("codeUrl", resultMap.get("code_url"));
            // 将付款码存入redis中2小时
            if (resultMap.get("result_code") != null) {
                redisTemplate.opsForValue().set(orderId.toString(), map, 120, TimeUnit.MINUTES);
            }

            return map;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 调用微信接口实现支付状态查询
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            // 1.根据orderId获取订单信息
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            // 2.提交封装参数
            Map paramMap = new HashMap();
            // 商户id
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            // 商户号
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            // 唯一的听单号
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            // 微信工具类随机生成的字符串
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            // 3.设置请求内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            // 4得到微信接口返回的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("支付状态resultMap: " + resultMap);
            // 5.返回数据
            return resultMap;

        } catch (Exception e) {
            return null;

        }
    }

    /**
     * 微信退款
     *
     * @param orderId
     * @return
     */
    @Override
    public Boolean refund(Long orderId) {

        try {
            // 1.获取支付信息的纪录
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            // 2.添加信息到退款纪录
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
            // 3.判断当前订单数据是否已经退款
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }
            // 4.调用微信接口实现退款 封装需要的参数
            Map<String, String> paramMap = new HashMap<>();
            // 公众账号ID
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            // 商户编号
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            // 随机字符串
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            // 微信订单号
            paramMap.put("transaction_id", paymentInfo.getTradeNo());
            // 商户订单编号
            paramMap.put("out_trade_no", paymentInfo.getOutTradeNo());
            // 商户退款单号
            paramMap.put("out_refund_no", "tk" + paymentInfo.getOutTradeNo());
            // paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            // paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");
            paramMap.put("refund_fee", "1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);
            // 5.调用接口类容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            // 6.设置证书信息
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();
            // 7.接受返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("微信退款返回数据resultMap: " + resultMap);
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
